#include "util.h"
#include <fstream>
#include <sstream>
#include <string.h>

using namespace std;

void util_split_filename(char *filename, char *base, char *ext)
{
	ext[0] = '\0';
	
	int len = strlen(filename);
	int i = len;
	while(--i && filename[i] != '.');
	
	base[0] = ext[0] = '\0';
	
	if(i && len > 2)
	{
		strncpy(base, filename, i);
		base[i] = 0;
		strncpy(ext, filename+i+1, len-i);
	}
}

string util_get_file_contents(const char *filename)
{
	ifstream is;
	stringbuf sb;
	char buff[129];
	int length;
		
	is.open (filename, ios::in);

	do
	{
		length = is.readsome(buff, 128);
		sb.sputn(buff, length);
	}
	while(length);
	
	is.close();
	
	return sb.str();
}

void util_replace_all(string &source, const string find, string replace)
{
	size_t findLen = find.length();
	size_t replaceLen = replace.length();
	size_t idx = 0;
	while((idx = source.find(find, idx)) != string::npos)
	{
		source.replace(idx, findLen, replace);
		idx += replaceLen;
	}
}

vector<string> util_split_string(string str, string delims)
{
	vector<string> comps;
	
	size_t i = 0;
	size_t j = str.find_first_of(delims);
	while(j != string::npos)
	{
		string comp = str.substr(i, j-i);
		comps.push_back(comp);
		i = j + 1;
		j = str.find_first_of(delims, i);
	}
	
	string comp = str.substr(i);
	comps.push_back(comp);
	
	return comps;
}

set<int> util_expand_bitset(string bitsetStr)
{
	set<int> setbits;
	vector<string> comps = util_split_string(bitsetStr, ",");
	int len = comps.size();
	int base = 0;
	for(int i=0; i<len; i++, base+=24)
	{
		int num;
		const char* comp = comps[i].c_str();
		if(sscanf(comp, "%i", &num) != EOF)
		{
			for(int b=0; b<24; b++)
			{
				if(num & 1<<b)
					setbits.insert(base+b);
			}
		}
	}
	return setbits;
}
